<template>
  <div class="role-container">
    <!-- 搜索框 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="formInline">
        <el-form-item label="角色名称">
          <el-input v-model="formInline.roleName" style="width: 180px" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item label="权限字符">
          <el-input v-model="formInline.roleKey" style="width: 180px" placeholder="请输入权限字符" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">搜索</el-button>
          <el-button @click="restForm()">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <div class="table-header">
        <el-button type="primary" @click="handleAdd"> 新增</el-button>
        <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
      </div>

      <el-table
        ref="multipleTableRef"
        :data="tableData"
        row-key="roleId"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" width="80" />
        <el-table-column property="roleName" label="角色名称" width="100" />
        <el-table-column property="roleKey" label="权限字符" width="160" />
        <el-table-column property="roleSort" label="显示顺序" width="120" />
        <el-table-column label="状态" width="120" align="center">
<!--          <template #default="scope">-->
<!--            <el-switch v-model="scope.row.status" inline-prompt-->
<!--              active-text="启用" inactive-text="禁用"-->
<!--              :active-value="'0'" :inactive-value="'1'"/>-->
<!--          </template>-->
          <template #default="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
              {{ scope.row.status === '0' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center"/>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)" style="margin-left: 10px">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[2, 5, 10, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 15px; text-align: right"
      />
    </el-card>

    <el-dialog v-model="dialogFormVisible" :title="dialogType==='add'?'添加角色':'编辑角色'" width="400px" :close-on-click-modal="false" draggable>
      <el-form :model="roleForm" ref="roleFormRef" :rules="roleFormRules" label-width="100px" :disabled="formLoading">
        <el-form-item label="角色ID" prop="id" v-if="dialogType === 'edit'"  class="hidden-id">
          <el-input v-model="roleForm.roleId" disabled />
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" :disabled="dialogType === 'edit'"/>
          <div class="form-hint" v-if="dialogType === 'add'">
            角色名称长度为2-10个字符，创建后不可修改
          </div>
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input
            v-model="roleForm.roleKey"
            placeholder="请输入权限字符（如：admin）"
          />
        </el-form-item>
        <el-form-item label="显示顺序" prop="roleSort">
          <el-input v-model.number="roleForm.roleSort" placeholder="请输入显示顺序（数字）" type="number" min="1"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="roleForm.status" inline-prompt
                     active-text="开启" inactive-text="关闭"
                     :active-value="'0'" :inactive-value="'1'"
          />
        </el-form-item>
        <el-form-item label="创建时间" v-if="dialogType === 'edit'">
          <el-input v-model="roleForm.createTime" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="formLoading">
            {{ dialogType === 'add' ? '添加' : '编辑' }}
          </el-button>
        </div>
      </template>

      <el-form-item label="权限分配">
        <el-tree
          v-model="selectedMenuIds"
          :data="menuList"
          show-checkbox
          node-key="menuId"
          check-strictly
          :props="defaultProps"
          class="permission-tree"
        />
        <div class="form-hint">
          请为角色分配可访问的菜单权限，勾选父节点会自动勾选所有子节点
        </div>
      </el-form-item>

    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import type { FormInstance, TableInstance } from 'element-plus'
import { ElMessage, ElMessageBox, FormRules } from 'element-plus'
import {Edit, Delete, Menu} from '@element-plus/icons-vue'
import {getRoleList, addRole, updateRole, deleteRole, getRolePermissions,assignRolePermissions} from '@/api/role'
import {getMenuTree} from "@/api/menu";


// 类型定义
interface Role {
  roleId: number | string  // 与后端返回的roleId一致
  roleName: string
  roleKey: string
  roleSort: number
  status: '0' | '1'
  createTime: string
}

// 添加和修改相关
const dialogFormVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const roleFormRef = ref<FormInstance>()
const formLoading = ref(false)
const roleForm = reactive({
  roleId: '',
  roleName: '',
  roleKey: '',
  roleSort: 1,
  status: '0',
  createTime: ''
})

// 菜单树数据
const menuList = ref<Menu[]>([])
// 选中的菜单ID（权限）
const selectedMenuIds = ref<(number | string)[]>([])
// 菜单树配置
const defaultProps = {
  children: 'subMenus',
  label: 'menuName'
}

// 原始角色数据
const originalRoleList = ref<Role[]>([
  { id: 1, roleName: '行政主管', roleKey: 'admin', roleSort: 1, status: '1', createTime: '2025-08-01 09:00:00' },
  { id: 2, roleName: '律所主任', roleKey: 'director', roleSort: 2, status: '1', createTime: '2025-08-01 09:10:00' },
  { id: 3, roleName: '律师', roleKey: 'lawyer', roleSort: 3, status: '1', createTime: '2025-08-01 09:20:00' }
])

// 表格相关
const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<Role[]>([])
const tableData = reactive<Role[]>([])
const loading = ref(false)

// 分页参数
const pagination = reactive({
  current: 1,
  pageSize: 2,
  total: originalRoleList.value.length
})

// 搜索表单
const formInline = reactive({
  roleName: '',
  roleKey: ''
})

// 页面挂载时加载数据
onMounted(() => {
  getRolesByCondition()
  loadMenuTree()
})

// 加载菜单树数据
const loadMenuTree = () => {
  getMenuTree().then(res => {
    menuList.value = res.data
  }).catch(error => {
    ElMessage.error('加载权限菜单失败: ' + error.message)
  })
}


// 打开添加弹窗
function handleAdd() {
  dialogType.value = 'add'
  if (roleFormRef.value) roleFormRef.value.resetFields()
  Object.assign(roleForm, {
    id: '',
    roleName: '',
    roleKey: '',
    roleSort: 1,
    status: '0',
    createTime: ''
  })
  dialogFormVisible.value = true
}

// 打开编辑弹窗
function handleEdit(index: number, row: Role) {
  dialogType.value = 'edit'
  if (roleFormRef.value) roleFormRef.value.resetFields()
  Object.assign(roleForm, {
    roleId: row.roleId,
    roleName: row.roleName,
    roleKey: row.roleKey,
    roleSort: row.roleSort,
    status: row.status,
    createTime: row.createTime
  })

  // 新增：获取并回显已有权限
  getRolePermissions(row.roleId).then(res => {
    selectedMenuIds.value = res.data.map(item => item.menuId)
  })

  dialogFormVisible.value = true
}

// 提交表单
function submitForm() {
  roleFormRef.value?.validate((valid) => {
    if (!valid) return

    formLoading.value = true
    const params = { ...roleForm }
    const request = dialogType.value === 'add' ? addRole : updateRole

    request(params).then(res => {
      // 新增：获取角色ID（新增时从返回结果取，编辑时直接用表单的roleId）
      const roleId = dialogType.value === 'add' ? res.data.roleId : roleForm.roleId

      // 提交权限关联
      return assignRolePermissions({
        roleId,
        menuIds: selectedMenuIds.value // 选中的菜单ID数组
      })
    }).then(() => {
      ElMessage.success(dialogType.value === 'add' ? '添加角色及权限成功' : '编辑角色及权限成功')
      dialogFormVisible.value = false
      getRolesByCondition()
      // 重置选中的权限
      selectedMenuIds.value = []
    }).catch(error => {
      ElMessage.error(`${dialogType.value === 'add' ? '添加' : '编辑'}失败: ${error.message}`)
    }).finally(() => {
      formLoading.value = false
    })
  })
}

// 删除相关
function handleDelete(row: Role) {
  confirmDelete([row.roleId])
}

function handleBatchDelete() {
  if (multipleSelection.value.length > 0) {
    const ids = multipleSelection.value.map(item => item.roleId)
    confirmDelete(ids)
  } else {
    ElMessage.error("请选择要删除的角色")
  }
}

function confirmDelete(ids: (number | string)[]) {
  ElMessageBox.confirm(
    '确定要删除选中的角色吗？删除后不可恢复',
    '消息',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    await deleteRole(ids)
    // 更新原始数据
    originalRoleList.value = originalRoleList.value.filter(
      item => !ids.includes(item.id)
    )
    ElMessage({ type: 'success', message: '删除完成' })
    pagination.current = 1
    getRolesByCondition()
  }).catch(() => {
    ElMessage({ type: 'info', message: '删除取消' })
  })
}

// 搜索和重置
const onSubmit = () => {
  pagination.current = 1
  getRolesByCondition()
}

function restForm() {
  formInline.roleName = ""
  formInline.roleKey = ""
  pagination.current = 1
  getRolesByCondition()
}

// 表格数据加载
function getRolesByCondition() {
  loading.value = true
  const params = {
    ...formInline,
    page: pagination.current,
    pageSize: pagination.pageSize
  }

  // 调用真实接口
  getRoleList(params).then(res => {
    const { list, total } = res.data // 假设后端返回{list: [], total: 0}
    tableData.length = 0
    tableData.push(...list)
    pagination.total = res.data.total
  }).catch(error => {
    ElMessage.error('查询失败: ' + error.message)
  }).finally(() => {
    loading.value = false
  })
}

// 分页事件
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  pagination.current = 1
  getRolesByCondition()
}

const handleCurrentChange = (val: number) => {
  pagination.current = val
  getRolesByCondition()
}

// 选择事件
const handleSelectionChange = (val: Role[]) => {
  multipleSelection.value = val
}

// 表单验证规则
const roleFormRules = reactive<FormRules>({
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 10, message: '角色名称长度需在2-10个字符之间', trigger: 'blur' }
  ],
  roleKey: [
    { required: true, message: '请输入权限字符', trigger: 'blur' },
    { pattern: /^[a-z]+$/, message: '权限字符仅支持小写字母', trigger: 'blur' }
  ],
  roleSort: [
    { required: true, message: '请输入显示顺序', trigger: 'blur' },
    { type: 'number', min: 1, message: '显示顺序必须为大于0的整数', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
})
</script>

<style scoped>
.role-container {
  width: 100%;
  height: 100%;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.filter-card {
  /*border-radius: 10px;*/
  margin-bottom: 5px;
}

.table-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 15px;
  gap: 10px;
}

.form-hint {
  color: #666;
  font-size: 12px;
  margin-top: 5px;
}

.table-foot {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-top: 10px;
  margin-left: 40px;
}

/* 如果完全不需要显示角色ID，可隐藏 */
.hidden-id {
  display: none;
}

</style>

